﻿using KBEngine;
using UnityEngine;
using System; 
using System.IO;  
using System.Collections; 
using System.Collections.Generic;
using System.Linq;
using UnityEngine.SceneManagement;

// 个人信息（头像、昵称、等级、经验、金币、宝石）
class UserInfo
{
    public int IconId = 0;
    public string Name = "";
    public int Level = 0;
    public ulong Exp = 0;
    public uint GoldNum = 0;
    public uint DiamondNum = 0;
}

public class UI : MonoBehaviour 
{
    // 辅助类
	public static UI inst;  
    public World thisWorld; // 控制器
    public int MaxChatRecordCount = 10;

    // 文本
	private string stringAccount = "";
	private string stringPasswd = "";
	private string labelMsg = "";
	private Color labelColor = Color.green;
    private string stringAvatarName = "";
    private LinkedList<string> chatrecords = new LinkedList<string>();
    private string sendChatText = "";
    private string stringCDKEY = "88888888";

    // 角色信息体
    private UserInfo ui_userinfo = new UserInfo();
    // 角色拥有数
    private UInt32 has_avatarCount = 0;

    // UI状态
    enum UISTATE
    {
        Login_UI,           // 登陆界面
        NewPlayer_UI,       // 创建角色界面
        OldPlayer_UI,       // 老玩家界面
        Lobby_UI,           // 大厅界面
        World_UI,           // 对战世界
    }

    // 聊天频道
    enum CHATCHANNEL
    {
        CHATCHANNEL_LOBBY,  // 大厅频道
        CHATCHANNEL_SPACE,  // 场景频道
        //CHATCHANNEL_P2P,    // 私聊频道

        CHATCHANNEL_MAX,    // 最大值
    }
    private CHATCHANNEL chatchannel = CHATCHANNEL.CHATCHANNEL_SPACE;

    private UISTATE ui_state = UISTATE.Login_UI;

	public bool showReliveGUI = false;
	private bool startRelogin = false;
    private bool showCDKEY = false;

    // 游戏房间
    private string[] spacelist = null;
    private string createRoomType = "";

    void Awake() 
	 {
		inst = this;
        DontDestroyOnLoad(transform.gameObject);
	 }
	 
	// Use this for initialization
	void Start () 
	{
        thisWorld = GetComponent<World>();

		installEvents();
		SceneManager.LoadScene("login");
	}

    // 注册事件，给业务层调用
	void installEvents()
	{
		// common
		KBEngine.Event.registerOut("onKicked", this, "onKicked");
		KBEngine.Event.registerOut("onDisconnected", this, "onDisconnected");
		KBEngine.Event.registerOut("onConnectionState", this, "onConnectionState");
		
		// login
		KBEngine.Event.registerOut("onCreateAccountResult", this, "onCreateAccountResult");
		KBEngine.Event.registerOut("onLoginFailed", this, "onLoginFailed");
		KBEngine.Event.registerOut("onVersionNotMatch", this, "onVersionNotMatch");
		KBEngine.Event.registerOut("onScriptVersionNotMatch", this, "onScriptVersionNotMatch");
		KBEngine.Event.registerOut("onLoginBaseappFailed", this, "onLoginBaseappFailed");
		KBEngine.Event.registerOut("onLoginSuccessfully", this, "onLoginSuccessfully");
		KBEngine.Event.registerOut("onReloginBaseappFailed", this, "onReloginBaseappFailed");
		KBEngine.Event.registerOut("onReloginBaseappSuccessfully", this, "onReloginBaseappSuccessfully");
		KBEngine.Event.registerOut("onLoginBaseapp", this, "onLoginBaseapp");
		KBEngine.Event.registerOut("Loginapp_importClientMessages", this, "Loginapp_importClientMessages");
		KBEngine.Event.registerOut("Baseapp_importClientMessages", this, "Baseapp_importClientMessages");
		KBEngine.Event.registerOut("Baseapp_importClientEntityDef", this, "Baseapp_importClientEntityDef");
		
		// avatar
		KBEngine.Event.registerOut("onReqAvatarCount", this, "onReqAvatarCount");
		KBEngine.Event.registerOut("onCreateAvatarResult", this, "onCreateAvatarResult");
		KBEngine.Event.registerOut("onRemoveAvatar", this, "onRemoveAvatar");

        // user-info
        KBEngine.Event.registerOut("set_IconId", this, "set_IconId");
        KBEngine.Event.registerOut("set_PlayerName", this, "set_PlayerName");
        KBEngine.Event.registerOut("set_Level", this, "set_Level");
        KBEngine.Event.registerOut("set_Exp", this, "set_Exp");
        KBEngine.Event.registerOut("set_GoldNum", this, "set_GoldNum");
        KBEngine.Event.registerOut("set_DiamondNum", this, "set_DiamondNum");

        // chat
        KBEngine.Event.registerOut("onChat", this, "onChat");

        // space
        KBEngine.Event.registerOut("onSpaceList", this, "onSpaceList");
    }

    void OnDestroy()
	{
		KBEngine.Event.deregisterOut(this);
	}
	
	// Update is called once per frame
	void Update ()
	{
        if (Input.GetKeyUp(KeyCode.Space))
        {
			Debug.Log("KeyCode.Space");
			KBEngine.Event.fireIn("jump");
        }
	}

    // 新用户界面
    void onNewPlayerUI()
    {
        if (KBEngineApp.app.entity_type != "Account")
        {
            return;
        }
           
        if (GUI.Button(new Rect(Screen.width / 2 - 100, Screen.height - 40, 200, 30), "CreateAvatar-OK(创建完成)"))
        {
            if (stringAvatarName.Length > 1)
            {
                KBEngine.Event.fireIn("reqCreateAvatar", (Byte)1, stringAvatarName);
                info("Please wait...(请稍后...)");
            }
            else
            {
                err("avatar name is null(角色名称为空)!");
            }
        }
        stringAvatarName = GUI.TextField(new Rect(Screen.width / 2 - 100, Screen.height - 75, 200, 30), stringAvatarName, 20);
    }

    // 旧用户
    void onOldPlayerUI()
    {
        // 直接进入游戏
        KBEngine.Event.fireIn("selectAvatarGame");
        info("Please wait...(正在加载大厅...)");
        ui_state = UISTATE.Lobby_UI;
        return;
    }

    // 登陆界面
    void onLoginUI()
	{
		if(GUI.Button(new Rect(Screen.width / 2 - 100, Screen.height / 2 + 30, 200, 30), "Login(登陆)"))  
        {  
        	Debug.Log("stringAccount:" + stringAccount);
        	Debug.Log("stringPasswd:" + stringPasswd);
        	
			if(stringAccount.Length > 0 && stringPasswd.Length > 5)
			{
				login();
            }
			else
			{
				err("account or password is error, length < 6!(账号或者密码错误，长度必须大于5!)");
			}
        }

        if (GUI.Button(new Rect(Screen.width / 2 - 100, Screen.height / 2 + 70, 200, 30), "CreateAccount(注册账号)"))  
        {
            Debug.Log("stringAccount:" + stringAccount);
            Debug.Log("stringPasswd:" + stringPasswd);
            Debug.Log("stringCDKEY:" + stringCDKEY);

            if (stringAccount.Length > 0 && stringPasswd.Length > 5 && stringCDKEY.Length > 0)
            {
                createAccount();
            }
            else
            {
                err("account or password is error, length < 6!(账号或者密码错误，长度必须大于5!)");
            }
        }
        
		stringAccount = GUI.TextField(new Rect (Screen.width / 2 - 100, Screen.height / 2 - 90, 200, 30), stringAccount, 20);
		stringPasswd = GUI.PasswordField(new Rect (Screen.width / 2 - 100, Screen.height / 2 - 50, 200, 30), stringPasswd, '*');
        if(showCDKEY == true)
        {
            stringCDKEY = GUI.TextField(new Rect(Screen.width / 2 - 100, Screen.height / 2 - 10, 200, 30), stringCDKEY, 20);
        }
    }

    // 游戏大厅界面
    void onLobby()
    {
        // 个人信息（头像、昵称、等级、经验、金币）
        string personlInfo = "玩家信息:";
        personlInfo += "\n 头像id：;" + ui_userinfo.IconId;
        personlInfo += "\n 昵称:" + ui_userinfo.Name;
        personlInfo += "\n 等级:" + ui_userinfo.Level;
        personlInfo += "\n 经验:" + ui_userinfo.Exp;
        personlInfo += "\n 金币:" + ui_userinfo.GoldNum;
        personlInfo += "\n 宝石:" + ui_userinfo.DiamondNum;
        GUI.Label(GetRect(3, 4, 0, 0), personlInfo);

        if (GUI.Button(GetRect(5, 4, 0, 1), "(create room)"))
        {
            if(createRoomType.Length > 0)
            {
                KBEngine.Event.fireIn("selectspace", createRoomType, "");
                SceneManager.LoadScene("world");
                ui_state = UISTATE.World_UI;
            }
        }
        createRoomType = GUI.TextField(GetRect(5, 8, 0, 5), createRoomType, 20);

        //if (GUI.Button(GetRect(5, 4, 0, 2), "(进入对战)"))
        //{
        //    Debug.Log("enterDefaultSpace");
        //    // 请求默认场景
        //    KBEngine.Event.fireIn("enterDefaultSpace");
        //    // 加载默认场景
        //    SceneManager.LoadScene("world");
        //    ui_state = UISTATE.World_UI;
        //}

        if (spacelist != null)
        {
            for (int idx = 0; idx < spacelist.Length; ++idx)
            {
                if (spacelist[idx].Length == 0)
                    continue;

                if (GUI.Button(GetRect( 5, 10, 1, idx), spacelist[idx]))
                {
                    // 默认格式 场景类型:场景标识
                    string[] info = spacelist[idx].Split(':');
                    KBEngine.Event.fireIn("selectspace", info[0], info[1]);

                    SceneManager.LoadScene("world");
                    ui_state = UISTATE.World_UI;
                }
            }
        }
    }

    // 战斗世界
    void onWorldUI()
	{
        if(thisWorld.inWorld == false)
        {
            // 先创建实体
            thisWorld.inWorld = true;
        }

		if(showReliveGUI)
		{
			if(GUI.Button(new Rect(Screen.width / 2 - 100, Screen.height / 2, 200, 30), "Relive(复活)"))  
			{
				KBEngine.Event.fireIn("relive", (Byte)1);		        	
			}
		}
		
		UnityEngine.GameObject obj = UnityEngine.GameObject.Find("player(Clone)");
		if(obj != null)
		{
			GUI.Label(new Rect((Screen.width / 2) - 100, 20, 400, 100), "id=" + KBEngineApp.app.entity_id + ", position=" + obj.transform.position.ToString()); 
		}

        if (GUI.Button(GetRect(5, 1, 0, 0), "return"))
        {
            KBEngine.Event.fireIn("leavecurrspace");
            SceneManager.LoadScene("selavatars");
            ui_state = UISTATE.Lobby_UI;
            thisWorld.inWorld = false;
        }

    }

    // 聊天面板
    void onChatUI()
    {
        // 聊天记录
        GUI.Label(GetRect(3, 1, 1, 0), getChatRecords());
        // 选择聊天频道
        if (GUI.Button(GetRect(5, 3, 4, 0), GetChatChannel()))
        {
            //TODO:
        }
        // 聊天输入框
        sendChatText = GUI.TextField(GetRect(5, 3, 4, 1), sendChatText, 20);
        // 聊天发送
        if (GUI.Button(GetRect(5, 3, 4, 2), "发送"))
        {
            if (sendChatText == "")
            {
                err("聊天功能: 发送文本不能为空!");
            }
            else
            {
                if (chatchannel == CHATCHANNEL.CHATCHANNEL_SPACE)
                {
                    KBEngine.Event.fireIn("SpaceChat", sendChatText);
                }
                else if (chatchannel == CHATCHANNEL.CHATCHANNEL_LOBBY)
                {
                    KBEngine.Event.fireIn("LobbyChat", sendChatText);
                }
                sendChatText = "";
            }
        }
    }

    void OnGUI()  
    {  
        switch(ui_state)
        {
            case UISTATE.Login_UI:
                {
                    onLoginUI();
                    break;
                }
            case UISTATE.NewPlayer_UI:
                {
                    onNewPlayerUI();
                    break;
                }
            case UISTATE.OldPlayer_UI:
                {
                    onOldPlayerUI();
                    break;
                }
            case UISTATE.Lobby_UI:
                {
                    onLobby();
                    onChatUI();
                    if (chatchannel != CHATCHANNEL.CHATCHANNEL_LOBBY)
                    {
                        chatchannel = CHATCHANNEL.CHATCHANNEL_LOBBY;
                        info("");
                    }
                    break;
                }
            case UISTATE.World_UI:
                {
                    onWorldUI();
                    onChatUI();
                    if (chatchannel != CHATCHANNEL.CHATCHANNEL_SPACE)
                    {
                        chatchannel = CHATCHANNEL.CHATCHANNEL_SPACE;
                        info("");
                    }
                    break;
                }
            default:
                return;
        }
   		
		if(KBEngineApp.app != null && KBEngineApp.app.serverVersion != "" 
			&& KBEngineApp.app.serverVersion != KBEngineApp.app.clientVersion)
		{
			labelColor = Color.red;
			labelMsg = "version not match(curr=" + KBEngineApp.app.clientVersion + ", srv=" + KBEngineApp.app.serverVersion + " )(版本不匹配)";
		}
		else if(KBEngineApp.app != null && KBEngineApp.app.serverScriptVersion != "" 
			&& KBEngineApp.app.serverScriptVersion != KBEngineApp.app.clientScriptVersion)
		{
			labelColor = Color.red;
			labelMsg = "scriptVersion not match(curr=" + KBEngineApp.app.clientScriptVersion + ", srv=" + KBEngineApp.app.serverScriptVersion + " )(脚本版本不匹配)";
		}
		// 提示语
		GUI.contentColor = labelColor;
		GUI.Label(new Rect((Screen.width / 2) - 100, 40, 400, 100), labelMsg);
        // 版本信息
		GUI.Label(new Rect(0, 5, 400, 100), "client version: " + KBEngine.KBEngineApp.app.clientVersion);
		GUI.Label(new Rect(0, 20, 400, 100), "client script version: " + KBEngine.KBEngineApp.app.clientScriptVersion);
		GUI.Label(new Rect(0, 35, 400, 100), "server version: " + KBEngine.KBEngineApp.app.serverVersion);
		GUI.Label(new Rect(0, 50, 400, 100), "server script version: " + KBEngine.KBEngineApp.app.serverScriptVersion);
	}  
	
    // 平均画面为多块相同的Rect,参数为总行数，总列数，第几行，第几列
    private Rect GetRect(int totalRow, int totalCol, int IdxRow, int IdxCol)
    {
        // 从0开始，0行0列
        float width = (float)Screen.width / (float)totalCol;
        float height = (float)Screen.height / (float)totalRow;

        float x = width * (float)IdxCol;
        float y = height * (float)IdxRow;

        return new Rect(x, y, width, height);
    }

	public void err(string s)
	{
		labelColor = Color.red;
		labelMsg = s;
	}
	
	public void info(string s)
	{
		labelColor = Color.green;
		labelMsg = s;
	}
	
	public void login()
	{
		info("connect to server...(连接到服务端...)");
		KBEngine.Event.fireIn("login", stringAccount, stringPasswd, System.Text.Encoding.UTF8.GetBytes("kbengine_unity3d_demo"));
	}
	
	public void createAccount()
	{
		info("connect to server...(连接到服务端...)");
		
		KBEngine.Event.fireIn("createAccount", stringAccount, stringPasswd, stringCDKEY, System.Text.Encoding.UTF8.GetBytes("kbengine_unity3d_demo"));
	}
	
	public void onCreateAccountResult(UInt16 retcode, byte[] datas)
	{
		if(retcode != 0)
		{
			err("createAccount is error(注册账号错误)! err=" + KBEngineApp.app.serverErr(retcode));
			return;
		}
		
		if(KBEngineApp.validEmail(stringAccount))
		{
			info("createAccount is successfully, Please activate your Email!(注册账号成功，请激活Email!)");
		}
		else
		{
			info("createAccount is successfully!(注册账号成功!)");
		}
	}
	
	public void onConnectionState(bool success)
	{
		if(!success)
			err("connect(" + KBEngineApp.app.getInitArgs().ip + ":" + KBEngineApp.app.getInitArgs().port + ") is error! (连接错误)");
		else
			info("connect successfully, please wait...(连接成功，请等候...)");
	}
	
	public void onLoginFailed(UInt16 failedcode)
	{
		if(failedcode == 20)
		{
			err("login is failed(登陆失败), err=" + KBEngineApp.app.serverErr(failedcode) + ", " + System.Text.Encoding.ASCII.GetString(KBEngineApp.app.serverdatas()));
		}
		else
		{
			err("login is failed(登陆失败), err=" + KBEngineApp.app.serverErr(failedcode));
		}
	}
	
	public void onVersionNotMatch(string verInfo, string serVerInfo)
	{
		err("");
	}

	public void onScriptVersionNotMatch(string verInfo, string serVerInfo)
	{
		err("");
	}
	
	public void onLoginBaseappFailed(UInt16 failedcode)
	{
		err("loginBaseapp is failed(登陆网关失败), err=" + KBEngineApp.app.serverErr(failedcode));
	}
	
	public void onLoginBaseapp()
	{
		info("connect to loginBaseapp, please wait...(连接到网关， 请稍后...)");
	}

	public void onReloginBaseappFailed(UInt16 failedcode)
	{
		err("relogin is failed(重连网关失败), err=" + KBEngineApp.app.serverErr(failedcode));
		startRelogin = false;
	}
	
	public void onReloginBaseappSuccessfully()
	{
		info("relogin is successfully!(重连成功!)");
		startRelogin = false;
	}
	
	public void onLoginSuccessfully(UInt64 rndUUID, Int32 eid, Account accountEntity)
	{
		info("login is successfully!(登陆成功!)");
		SceneManager.LoadScene("selavatars");
        // 因为这里只是账号登陆，并非玩家信息获得，有可能是新或老玩家
	}

	public void onKicked(UInt16 failedcode)
	{
		err("kick, disconnect!, reason=" + KBEngineApp.app.serverErr(failedcode));

		SceneManager.LoadScene("login");
        // 被踢，返回登陆界面
		ui_state = UISTATE.Login_UI;
	}

	public void Loginapp_importClientMessages()
	{
		info("Loginapp_importClientMessages ...");
	}

	public void Baseapp_importClientMessages()
	{
		info("Baseapp_importClientMessages ...");
	}
	
	public void Baseapp_importClientEntityDef()
	{
		info("importClientEntityDef ...");
	}
	
	public void onReqAvatarCount(UInt32 avatarCount)
	{
        has_avatarCount = avatarCount;

        // 从登陆界面切换
        if(ui_state == UISTATE.Login_UI
            || ui_state == UISTATE.NewPlayer_UI)
        {
            if (has_avatarCount > 0)
            {
                // 进入游戏大厅
                ui_state = UISTATE.OldPlayer_UI;
                info("欢迎主人回来...");
                return;
            }
            else
            {
                // 需要创建角色
                ui_state = UISTATE.NewPlayer_UI;
                info("请问阁下如何称呼...");
                return;
            }
        }
        else
        {
            // 其他情况仅仅刷新用户数据
            // todo
        }
    }
	
	public void onCreateAvatarResult(Byte retcode, UInt32 avatarCount)
    {
		if(retcode != 0)
		{
			err("Error creating avatar, errcode=" + retcode);
			return;
		}
		
		onReqAvatarCount(avatarCount);
	}
	
	public void onRemoveAvatar(UInt64 dbid)
	{
		if(dbid == 0)
		{
			err("Delete the avatar error!(删除角色错误!)");
			return;
		}

        onReqAvatarCount(has_avatarCount - 1);
	}
	
	public void onDisconnected()
	{
		err("disconnect! will try to reconnect...(你已掉线，尝试重连中!)");
		startRelogin = true;
		Invoke("onReloginBaseappTimer", 1.0f);
	}
	
	public void onReloginBaseappTimer() 
	{
		if(ui_state == 0)
		{
			err("disconnect! (你已掉线!)");
			return;
		}
	
		KBEngineApp.app.reloginBaseapp();
		
		if(startRelogin)
			Invoke("onReloginBaseappTimer", 3.0f);
	}


    // 属性变化回调
    public void set_IconId(KBEngine.Entity entity, UInt16 iconId)
    {
        ui_userinfo.IconId = iconId;
    }

    public void set_Level(KBEngine.Entity entity, UInt16 level)
    {
        ui_userinfo.Level = level;
    }

    public void set_PlayerName(KBEngine.Entity entity, string name)
    {
        ui_userinfo.Name = name;
    }
    public void set_Exp(KBEngine.Entity entity, UInt64 exp)
    {
        ui_userinfo.Exp = exp;
    }
    public void set_GoldNum(KBEngine.Entity entity, UInt32 goldnum)
    {
        ui_userinfo.GoldNum = goldnum;
    }
    public void set_DiamondNum(KBEngine.Entity entity, UInt32 diamondnum)
    {
        ui_userinfo.DiamondNum = diamondnum;
    }

    // 聊天框相关
    public string getChatRecords()
    {
        string allRecords = "";
        int recordsIdx = 0;
        LinkedListNode<string> llnLastPrivous = chatrecords.Last;
        while (llnLastPrivous != null)
        {
            string currText = llnLastPrivous.Value;
            if (recordsIdx < MaxChatRecordCount)
            {
                allRecords += currText + "\n";
                ++recordsIdx;
            }

            llnLastPrivous = llnLastPrivous.Previous;
            if (recordsIdx >= MaxChatRecordCount)
            {
                chatrecords.Remove(currText);
            }
        } 

        return allRecords;
    }
    public void onChat(KBEngine.Entity entity, string text)
    {
        Debug.Log("onChat:" + text);
        chatrecords.AddLast(text);
    }
    private string GetChatChannel()
    {
        if(chatchannel == CHATCHANNEL.CHATCHANNEL_LOBBY)
        {
            return "大厅频道";
        }
        else if(chatchannel == CHATCHANNEL.CHATCHANNEL_SPACE)
        {
            return "场景频道";
        }
        return "null";
    }

    // 游戏房间
    public void onSpaceList(string[] newinfo)
    {
        spacelist = newinfo; // 刷新房间列表
    }
}
